package com.pactera.mavenweb.daoimpl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.pactera.mavenweb.dao.UserDao;
import com.pactera.mavenweb.entity.Group;
import com.pactera.mavenweb.entity.GroupRole;
import com.pactera.mavenweb.entity.UserGroup;
import com.pactera.mavenweb.entity.Role;
import com.pactera.mavenweb.entity.User;
import com.pactera.mavenweb.entity.UserRole;

/**
 * UserDao实现类
 * @author SteveXIE
 *
 */
@Service("userDao")
public class UserDaoImpl extends GenericDaoImpl<User> implements
	UserDao {
	
	public UserDaoImpl() {
		super(User.class);
	}

//	@Override
	@SuppressWarnings("unchecked")
	public int saveUser(User user) {
		try {
			this.insert(user);
			return 0;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
//	@Override
	@SuppressWarnings("unchecked")
	public User queryByName(String name) {
		String hql = "from User where name = ?";
		String[] strArray = {name};
		
		User user = queryForTopObject(hql, strArray);
		return user;
	}
	
//	@Override
	@SuppressWarnings("unchecked")
	public User queryByNameWithAuth(String name) {
		String hql = "from User where name = ?";
		String[] strArray = {name};
		
		User user = queryForTopObject(hql, strArray);
		
		// for debug
		for( UserGroup userGroup: user.getUserGroup() ) {
			System.out.println("Steve userGroup.getId() = " + userGroup.getId());
			System.out.println("Steve userGroup.getGroup().getGroupname() = " + userGroup.getGroup().getGroupname());
		}
		for( UserRole userRole: user.getUserRole() ) {
			System.out.println("Steve userRole.getId() = " + userRole.getId());
			System.out.println("Steve userRole.getRole().getRole() = " + userRole.getRole().getRole());
		}
		// for debug
		
		
		user.getUserRole();
		user.setAuthority(achieveAuthorities(user));
		
		return user;
	}
	
	private Set<String> achieveAuthorities(User user) {
		Set<String> authorities = new HashSet<String>();

		Group group = null;
		Role role = null;
		Set<UserGroup> userGroupSet = user.getUserGroup();
		
		if((userGroupSet != null) && (userGroupSet.size() > 0)) {
			for(UserGroup userGroup: userGroupSet) {
				group = userGroup.getGroup();
				Set<GroupRole> groupRoleSet = group.getGroupRole();
				
				for(GroupRole grouprole: groupRoleSet) {
					role = grouprole.getRole();
					authorities.add(role.getRole());
				}
			}
		}
		
		return authorities;
	}
}